package com.software.task.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.software.task.mapper.SubjectMapper;
import com.software.task.pojo.PageBean;
import com.software.task.pojo.Subject;
import com.software.task.service.SubjectService;
import com.software.task.utils.ThreadLocalUtil;
import jakarta.annotation.Resource;


import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * @author 浦慧慧
 * @since 2024/12/16 11：34
 * @version 1.0
 */
@Service
public class SubjectServiceImpl implements SubjectService {

    @Resource
    private SubjectMapper subjectMapper;

    /**
     * 新增课程批量保存
     *
     * @param subject 课程对象
     */
    @Override
    public int batchSave(List<Subject> subject) {
        //补充属性值

        return   subjectMapper.batchInsert(subject);
    }

    /**
     * 查询课程并且分页
     *
     * @param pageNum 页码
     * @param pageSize 页大小
     * @param categoryId 分类id
     * @param state 状态
     *              发布状态 已发布|草稿
     * @return 课程对象
     */
    @Override
    public PageBean<Subject> list(Integer pageNum, Integer pageSize, Integer categoryId, String state) {
        //创建pageBean对象
        PageBean<Subject> pageBean = new PageBean<>();
        //开启分页查询
        PageHelper.startPage(pageNum, pageSize);

        //调用mapper方法，查询分页数据
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        List<Subject> subjectList = subjectMapper.list(userId,categoryId, state);
        Page<Subject> page = (Page<Subject>) subjectList;
        //把subjectList封装到pageBean对象中
        pageBean.setTotal(page.getTotal());
        pageBean.setItems(page.getResult());
        return pageBean;
    }

    /**
     * 更新课程
     *
     * @param subject 课程对象
     */
    @Override
    public void update(Subject subject) {
        subject.setUpdateDateTime(LocalDateTime.now());
        subjectMapper.update(subject);

    }

    /**
     * 删除课程
     *
     * @param id 课程id
     */
    @Override
    public void delete(Integer id) {
        subjectMapper.delete(id);
    }

    /**
     * 根据id查询课程
     *
     * @param categoryId 课程分类id
     * @return 课程对象
     */
    @Override
    public Integer countByCategoryId(Integer categoryId) {
        return subjectMapper.countByCategoryId(categoryId);
    }

    /**
     * 列表查询
     *
     * @param subject 查询对象
     * @return 所有用户信息
     */
    @Override
    public List<Subject> getList(Subject subject) {
        return subjectMapper.getSubjectList(subject);
    }

    @Override
    public void add(Subject subject) {
        //补充属性值
        subject.setCreateDateTime(LocalDateTime.now());
        subject.setUpdateDateTime(LocalDateTime.now());
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        subject.setCreateUser(userId);
        subjectMapper.add(subject);
    }


}
